package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.dao.TaskDao;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
@Transactional
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }



    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }

    @Override
    public boolean create(TaskViewModel taskViewModel) {
        // 1 效验是否有未完成的工单
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        qw.eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode());
        qw.in(TaskEntity::getTaskStatus, Arrays.asList(1, 2));
        TaskEntity one = getOne(qw);
        if(one != null){
            throw new LogicException("存在未完成的工单");
        }

        // feign 接口调用， 获取售货机信息
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());

        // 判断工单类型
        int type = taskViewModel.getProductType();
        if(type == VMSystem.TASK_TYPE_DEPLOY && VMSystem.TASK_STATUS_CREATE.equals(vmInfo.getVmStatus())){
            throw new LogicException("售货机已投放");
        }
        if(type == VMSystem.TASK_TYPE_SUPPLY && !VMSystem.TASK_STATUS_CREATE.equals(vmInfo.getVmStatus())){
            throw new LogicException("售货机不是运营状态");
        }
        if((type == VMSystem.TASK_TYPE_REPAIR || type == VMSystem.TASK_TYPE_REVOKE) &&
                !VMSystem.TASK_STATUS_CREATE.equals(vmInfo.getVmStatus())) {
            throw  new LogicException("售货机不是运营状态");
        }

        // 按照年月日 +4 为当日序列号生成工单编码
        String taskCode = generateTaskCode();

        // 调用 user 微服务 获取当前用户信息
        UserVO user = userService.getUser(taskViewModel.getUserId());

        if(user == null){
            throw  new LogicException("未查找到执行人");
        }

        // 保存数据
        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        taskEntity.setTaskCode(taskCode);
        taskEntity.setTaskStatus(1);
        taskEntity.setUserName(user.getUserName());
        taskEntity.setRegionId(vmInfo.getRegionId());
        taskEntity.setAddr(vmInfo.getNodeAddr());

        boolean flag= save(taskEntity);
        if(!flag){
            throw new LogicException("添加失败请重新尝试");
        }

        // 补货工单
        if(type == 2){
            if(taskViewModel.getDetails() == null || taskViewModel.getDetails().size() == 0){
                throw new LogicException("没有补货详细信息");
            }
            List<TaskDetailsEntity> taskDetailsEntities = new ArrayList<>();
            for (TaskDetailsViewModel detail : taskViewModel.getDetails()) {
                TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(detail, taskDetailsEntity);
                taskDetailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsEntities.add(taskDetailsEntity);
            }

            boolean b = taskDetailsService.saveBatch(taskDetailsEntities);
            if(!b){
                throw new LogicException("添加失败请重新尝试");
            }
        }
        return true;
    }


    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }


}
